<template>
  <el-dialog
    :append-to-body="true"
    :close-on-click-modal="false"
    :title="'工程过程管理'"
    :visible.sync="visible"
    custom-class="ledger"
    fullscreen top="5vh"
    width="1200px"
    :before-close="cancelDialog">
    <div class="colums">
      <div class="colums_left">
        <div class="colums_left_middle">
          <div class="middleForm ledger">
            <el-form ref="dataForm" :model="form" class="el-dialog__body" label-width="100px">
              <div class="title">基本信息</div>
              <el-row>
                <el-col :span="12">
                  <el-form-item label-width="130px" label="关联项目名称: " :rules="{required: true, message: '关联项目不能为空', trigger: ['blur', 'change']}">
                    {{ form.projectName }}
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label-width="110px" label="勘探时间:" prop="explorationTime" :rules="{required: true, message: '勘探时间不能为空', trigger: ['blur', 'change']}">
                    <el-date-picker placement="bottom-start" v-model="form.explorationTime" type="date" placeholder="选择日期"
                                    format="yyyy-MM-dd" value-format="yyyy-MM-dd"></el-date-picker>
                  </el-form-item>
                </el-col>
              </el-row>
              <div class="title">工程影像</div>
              <el-row>
                <el-col >
                  <el-button icon="el-icon-plus" size="small" type="primary" @click="onAddItem('')">新建</el-button>
                    <el-button icon="el-icon-document-copy" @click="addSelectedRow">复制</el-button>
                    <el-button icon="el-icon-delete" @click="deleteSelectedRows">删除</el-button>
                  <el-button icon="el-icon-delete-solid" @click="clearTableData">删除全部</el-button>
                </el-col>
              </el-row>
              <el-row>
                <el-col>
                  <el-table
                    ref="table"
                    :data="tableData"
                    :model="tableData"
                    v-loading="loading"
                    style="width: 100%"
                    max-height="450"
                    highlight-current-row
                    @selection-change="updateSelectedRows"
                    @current-change="handleCurrentChange"
                  >
                    <el-table-column type="selection" width="55" align="center"></el-table-column>
                    <el-table-column label="序号" width="100">
                      <template #default="{ $index }">
                        <span>{{ $index + 1 }}</span>
                      </template>
                    </el-table-column>
                    <el-table-column label="资料名称">
                      <template #default="{ row }">
                        <el-input v-if="row.readStatus === 0" v-model="row.name" type="textarea" :autosize="{ minRows: 1}" placeholder="输入资料名称"></el-input>
                        <span v-if="row.readStatus !== 0">{{ row.name }}</span>
                      </template>
                    </el-table-column>
                    <el-table-column>
                      <template slot="header" slot-scope="scope">
                        <div style="width: 185px; display: inline-block; margin-right: 16px;">上传时间（为空时则为保存时间）</div>
                        <el-button icon="el-icon-refresh-left" size="mini" circle style="border-radius: 3px;" @click="resetUpdateTime">清空时间</el-button>
                      </template>
                      <template #default="{ row }">
                        <el-date-picker v-if="row.readStatus === 0" placement="bottom-start" v-model="row.updateTime" type="datetime" format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss"></el-date-picker>
                        <span v-if="row.readStatus !== 0">{{ row.updateTime }}</span>
                      </template>
                    </el-table-column>
                    <el-table-column label="勘探资料上传" width="280">
                      <template #default="{ row, $index }">
                        <el-upload
                          class="upload-demo"
                          ref="upload"
                          action="/admin/sys-file/upload"
                          :headers="{Authorization}"
                          :on-success="(e) => handleSuccess(e, $index)"
                          :on-preview="(e) => handlePreview(e, $index)"
                          :on-remove="(file, fileList) => handleRemove(file, fileList, $index)"
                          :show-file-list="true"
                          :file-list="row.fileList">
                          <i v-if="row.readStatus === 0" class="el-icon-paperclip" style="color: #409EFF;"></i>
                        </el-upload>
                      </template>
                    </el-table-column>
                  </el-table>
                </el-col>
              </el-row>
            </el-form>
            <span slot="footer" class="dialog-footer">
              <el-button icon="el-icon-close" size="small" @click="cancelDialog">关闭</el-button>
              <el-button icon="el-icon-check" size="small" type="primary" @click="submit">保存</el-button>
              <el-button icon="el-icon-check" size="small" type="primary" @click="imageSubmit">提交</el-button>
            </span>
          </div>
        </div>
      </div>
    </div>
    <div v-if="fileVisible" class="fileClass" >
      <div class="fileClose"></div>
      <el-carousel indicator-position="outside" :autoplay="false" :initial-index="initialIndex">
        <el-carousel-item v-for="(item, i) in filesList" :key="i" class="fileClass-col">
          <img v-if="item.type === 'img'" :src="item.url" style="max-width: 100%;max-height:100%" @click="fileVisible = false" />
          <video v-if="item.type === 'video'" :src="item.url" controls data-setup='{"fluid": true}' @click="fileVisible = false"></video>
        </el-carousel-item>
      </el-carousel>
    </div>

    <FormTransfer :transferDialog="transferDialog" :transferDialogType="transferDialogType" :multiple="transferDialogMultiple" :transferCurrent="transferCurrent" @transferData="transferDataHandle" @closeTransfer="closeTransfer"/>
    <ChoseProject ref="ChoseProject" @setValue="projectDataHandle"/>
  </el-dialog>
</template>

<script>
import {mapGetters} from "vuex";
import ChoseProject from "@/components/audited/ChoseProject.vue";
import FormTransfer from "@/components/form/transfer";
import WebDocument from '@/components/form/webDocument.vue';
import {getObj, submit, imageSubmit, getFileList} from "@/api/adis/engineering/image";
import Template from "@/views/adis/base/template.vue";

export default {
  components: {
    Template,
    FormTransfer,
    ChoseProject,
    WebDocument,
  },
  dictTypes: ['audit_type'],
  data() {
    return {
      visible: false,
      loading: false,
      projectDisplay: false,
      multiple: false,
      transferDialog: false,
      transferDialogType: '',
      transferDialogTypeArr: [],
      transferDialogMultiple: false,
      transferCurrent: {},

      form: {},

      tableData: [
        {
          name: '',
        }
      ],// 资料清单数据
      selectedRows: [], // 存储选中的行数据
      selectedRow: {},
      Authorization: '',
      fileVisible: false,
      filesList: [],
      initialIndex: 0
    }
  },
  computed: {
    ...mapGetters(["permissions", 'userInfo']),
  },
  watch: {
    // 检测资料清单，如果被全数删除，立即补充一条空的清单
    tableData(newVal){
      if ((!newVal || newVal.length <= 1) && this.tableData.length <= 0){
        const templateData = {
          name : '',
        };
        this.onAddItem(templateData)
      }
    },
  },
  created() {
    this.Authorization = 'Bearer ' + this.$store.getters.access_token
  },
  methods: {
    // -- 页面初始化
    init(params, type) {
      if (params && !type ) this.projectDisplay = true
      this.$nextTick(() => {
        if (params && params.projectId) {
          getObj(params.imageId).then((imageResponse) => {
            this.$set(this, "form", imageResponse.data.data);
            this.visible = true // 更改页面状态

            // 打开页面后再加载tableData,避免出现文本框渲染错误的情况
            if (this.form.attachments && this.form.attachments.length > 0){
              this.loading = true
              setTimeout(() => {
                this.tableData = this.form.attachments || []
                this.tableData.forEach(item => {
                  item.fileList = []
                  item.attachments.forEach(col => {
                    item.fileList.push({name: col.fileName, url: col.fileUrl})
                  })
                })
                this.loading = false
              }, 500)
            }
          })
        }
      })
    },

    // -- 资料上传
    resetUpdateTime(){
      this.tableData.forEach(selectedRow => {
        selectedRow.updateTime = '';
      })
    },
    handleRemove(file, fileList, i) {
      this.tableData[i].fileList.forEach((item, v) => {
        if (file.url === item.url) this.tableData[i].fileList.splice(v, 1)
      })
    },
    handlePreview(file, i) {
      const currentFile = file.url ? file.url : file.response.data.url
      if (this.IsPicture(currentFile) || this.IsVideo(currentFile)) {
        this.filesList = this.tableData[i].fileList.filter(item => this.IsPicture(item.url) || this.IsVideo(item.url))
        this.filesList.forEach((item, v) => {
          if (this.IsPicture(item.url) || this.IsVideo(item.url)) {
            if (currentFile === item.url) {
              this.initialIndex = v
            }
            if (this.IsPicture(item.url)) item.type = 'img'
            if (this.IsVideo(item.url)) item.type = 'video'
          }
        })
        console.log(this.initialIndex)
        this.fileVisible = true
      } else {
        window.open(file.url ? file.url : file.response.data.url)
      }
    },
    handleSuccess(e, v) {
      if (!this.tableData[v].fileList) {
        this.tableData[v].fileList = [{url: e.data.url, name: e.data.fileName}]
      } else {
        this.tableData[v].fileList.push({url: e.data.url, name: e.data.fileName})
      }
    },

    /** 关联项目  - Head - */
    showProjectDialog() {
      this.$nextTick(() => {
        this.$refs.ChoseProject.initParams({isEngineering: true, isTermination: false});
      })
    },
    projectDataHandle(row){
      this.form = row;
      getFileList().then((res)=>{
        this.tableData = []
        res.data.data.forEach(file => {
          this.onAddItem(file)
        })
      })
    },
    /** 关联项目  - foot - */

    // -- 资料清单
    addSelectedRow() {
      if (this.selectedRows.length > 0) {
        this.selectedRows.forEach((selectedRow) => {
          const index = this.tableData.indexOf(selectedRow);
          if (index !== -1) {
            this.onAddItem(selectedRow)
          }
        });
       } else if (Object.keys(this.selectedRow).length !== 0){
        this.onAddItem(this.selectedRow)
      } else {
        this.$message({
          type: "warning",
          message: "请选择一条数据!"
        });
      }
    },
    clearTableData() {
      this.tableData = [];
    },
    onAddItem(val) {
      // 添加新资料
      if (!this.tableData) this.tableData = []
      this.tableData.push({
        name: val.name || '',
        updateTime: val.updateTime || '',
        fileList: val.fileList || [],
        readStatus: val.readStatus || 0,
      })
    },
    deleteSelectedRows() {
      if (this.selectedRows.length > 0) {
        this.selectedRows.forEach((selectedRow) => {
          const index = this.tableData.indexOf(selectedRow);
          if (index !== -1) {
            this.tableData.splice(index, 1);
          }
        });
       } else if (Object.keys(this.selectedRow).length !== 0){
        const index = this.tableData.indexOf(this.selectedRow);
        if (index !== -1) {
          this.tableData.splice(index, 1);
        }
      } else {
        this.$message({
          type: "warning",
          message: "请选择一条数据!"
        });
      }
    },
    updateSelectedRows(selection) {
      this.selectedRows = selection;
    },
    handleCurrentChange(selection){
      this.selectedRow = selection;
    },

    // 表单保存
    submit() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.handleFormData();
          this.loading = true;
          submit(this.form).then(() => {
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.cancelDialog();
          }, () => {
            this.loading = false;
          });
          console.log(this.form)
        } else {
          return false;
        }
      });
    },

    // 表单提交
    imageSubmit() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.handleFormData();
          this.loading = true;
          imageSubmit(this.form).then(() => {
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.cancelDialog();
          }, () => {
            this.loading = false;
          });
          console.log(this.form)
        } else {
          return false;
        }
      });
    },

    handleFormData(){
      this.fileList && this.fileList.map((file) => {
        this.form.fileUrl = file.response ? file.response.data.url : file.url
      });
      let count = 0
      try{
        this.tableData.forEach((item, i) => {
          if(item.name === ''){
            this.$message({
              type: "warning",
              message: '第' + (i + 1) + "行资料名称不能为空"
            });
            count++
            throw Error();
          }
        })
      }catch(e){
        console.log(e)
      }
      if (count > 0) return
      this.form.attachments = []
      this.tableData.forEach((item, i) => {
        item.attachments = []
        if (item.fileList){
          item.fileList.forEach(file => {
            item.attachments.push({fileName: file.name, fileUrl: file.url})
          })
        }
        this.form.attachments.push(item)
      })
      if(this.form.tenureDates){
        this.form.tenureStartDate = this.form.tenureDates[0]
        this.form.tenureEndDate = this.form.tenureDates[1]
      }
    },

    // 重置表单
    cancelDialog() {
      this.$emit('cancelDialog', {})
      this.$refs['dataForm'].resetFields()
      this.clearTableData()
      this.visible = false
    },

    // -- 穿梭框
    showTransferDialog(transferDialogArr, transferDialogType, transferDialogMultiple, transferDialogQuery) {
      this.transferDialogArr = transferDialogArr; // 表单字段
      this.transferDialogType = transferDialogType; // 判断类型user:人员，unit:职位，department:部门,company:单位,plan:计划等
      this.transferDialogMultiple = transferDialogMultiple; // 是否多选
      if (transferDialogType === 'company') {
        this.transferCurrent.type = transferDialogQuery;
      }
      if (transferDialogType === 'user') {
        if(!transferDialogQuery) {
          this.$message({
            type: "warning",
            message: "请先选择单位!"
          });
          return
        }
        this.transferCurrent.deptId = transferDialogQuery;
      }
      //重组数组name和id
      this.transferCurrent.currentval = []
      if(this.form[transferDialogArr[0]]) {
        if (this.form[transferDialogArr[0]].indexOf(',') > -1) {
          this.form[transferDialogArr[0]].split(',').forEach((item, i) => {
            this.transferCurrent.currentval.push({name: this.form[transferDialogArr[1]].split(',')[i], id: item})
          })
        } else {
          this.transferCurrent.currentval = [{name: this.form[transferDialogArr[1]], id: this.form[transferDialogArr[0]]}]
        }
      }
      this.transferDialog = true;
    },
    closeTransfer() {
      this.transferDialog = false
      this.transferDialogType = ''
    },
    // 已选定数据的更新判断
    transferDataHandle(e) {
      this.transferDialog = false
      let currentval = [], currentLabel = []
      if (e.list.length > 0) {
        if (e.list.length > 1) {
          e.list.forEach(item => {
            currentval.push(item.id)
            currentLabel.push(item.name)
          })
        } else {
          currentval = [e.list[0].id]
          currentLabel = [e.list[0].name]
        }
        this.$set(this.form, this.transferDialogArr[0], currentval.join(','))
        this.$set(this.form, this.transferDialogArr[1], currentLabel.join(','))
      } else { // 如果返回的数据为空，也将当前页面数值清空
        this.$set(this.form, this.transferDialogArr[0], '')
        this.$set(this.form, this.transferDialogArr[1], '')
      }
      this.transferDialogType = ''
    },
    wordFileHandle(e) {
      this.$set(this.form, "wordFile", e.wordFile);
      this.$set(this.form, "imageId", e.id);
    },
    IsPicture(file) {
      let strFilter=".jpeg|.gif|.jpg|.png|.bmp|.pic|.svg|.svg|.webp|";
      if(file.indexOf(".")>-1){
        var p = file.lastIndexOf(".");
        var strPostfix=file.substring(p,file.length) + '|';
        strPostfix = strPostfix.toLowerCase();
        if(strFilter.indexOf(strPostfix)>-1)
        {
          return true;
        }
      }
      return false;
    },
    IsVideo(file) {
      let strFilter=".mp4|.avi|.mov|.wmv|";
      if(file.indexOf(".")>-1){
        var p = file.lastIndexOf(".");
        var strPostfix=file.substring(p,file.length) + '|';
        strPostfix = strPostfix.toLowerCase();
        if(strFilter.indexOf(strPostfix)>-1)
        {
          return true;
        }
      }
      return false;
    }
  }
}
</script>
<style>
  .fileClass {
    position: fixed;
    z-index: 1;
    top: 0;
    left: 0;
    width:100vw;
    height: 100vh;
    background: rgba(0,0,0,0.5);
  }
  .fileClass-col {
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .el-carousel__container {
    height: 100vh;
  }
</style>
